package com.woniuxy.shirocore;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.env.BasicIniEnvironment;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;


public class AuthzPermBasicDemo {
    public static void main(String[] args) {
        //1.读取配置文件
        BasicIniEnvironment basicIniEnvironment = new BasicIniEnvironment("classpath:ini/shiro-authz.ini");
        //2.创建SecurityManager，中央大脑
        SecurityManager securityManager = basicIniEnvironment.getSecurityManager();
        //3.使用工具类，该工具类，必须注入securityManager
        SecurityUtils.setSecurityManager(securityManager);
        //4.通过工具类 创建subject
        Subject subject = SecurityUtils.getSubject();
        //5.模拟前端传入后台的账号，通过login方法，交给SecurityManager自己去帮我检查是否正确
        subject.login(new UsernamePasswordToken("zhangsan","654321"));
        //6.如果登录成功,isAuthenticated() 过去式，true表示登录过了。false
        System.out.println(subject.getPrincipal()+"登录成功："+subject.isAuthenticated());
        //7.进行授权
        if (subject.isAuthenticated()){
            //8.角色权限判断
            try {
                subject.checkRole("manager");
                //……继续写业务逻辑，否则直接抛出异常
                subject.checkPermission("user:findAll");
                boolean manager = subject.hasRole("manager");
                if (manager){
                    System.out.println(subject.getPrincipal()+"用户有manager角色");
                }
            }catch (AuthorizationException e){
                System.err.println("该用户没有这个权限。"+e.getMessage());
            }
        }
    }
}
